//
//  JrdChapterViewController.m
//  iMandarin
//
//  Created by longcheng on 16/8/6.
//  Copyright © 2016年 Singro. All rights reserved.
//

#import "JrdChapterViewController.h"
#import "JZCourseDetailModel.h"
#import "JrdCommon.h"
#import "CKHttpCommunicate.h"
#import "Reachability.h"
#import "JZStepListModel.h"
#import "JZClassListModel.h"
#import "JrdNodeModel.h"
#import "MJRefresh.h"
#import "JrdCourseChpaterCellTableViewCell.h"
#import "JrdChapterNodeViewController.h"
#import "JrdChapterModel.h"
@interface JrdChapterViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSMutableArray* chapterListArray;
    NSInteger vHeadIndex;
    JZCourseDetailModel *_jzCourseDM;
    NSInteger vCourseInfoCellHeight;

}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SCBarButtonItem *leftBarItem;
@property (nonatomic, strong) UITextView *learn_time_label;

@end

@implementation JrdChapterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.sc_navigationItem.leftBarButtonItem = self.leftBarItem;

}

- (void)viewDidAppear:(BOOL)animated{
    self.sc_navigationItem.title = _coursemodel.courseName;//NSLocalizedString(@"v2_my_study",nil);//@"我们学习";
}

- (void)loadView{
    [super loadView];
    [self configureNav];
    [self initData];
    [self initTableView];
    //fake audio list
    //[self dataJson];
    
}

- (void)configureNav{
    self.leftBarItem = [[SCBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ico_back"] highlight:[UIImage imageNamed:@"btn-back-normal"] style:SCBarButtonItemStylePlain handler:^(id sender) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)initTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-44) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    [self setupTableview];
    
}



- (void)initView{
    self.learn_time_label = [[UITextView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, 0, SCREEN_WIDTH/2, 45)];
    self.learn_time_label.textAlignment=NSTextAlignmentRight;
    
}

- (void)initData{
    chapterListArray = [[NSMutableArray alloc] init];
    vHeadIndex = 0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)loadNewData{
    //end refersh because use fake data
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getCourseChapterData];
    });
}

- (void)getCourseChapterData{
    //get chapter data from network
    NSDictionary *parameter = @{@"mod":@"course",
                                @"act":@"info",
                                @"do":@"getClassList",
                                @"sid":self.coursemodel.SID,
                                @"courseid":self.coursemodel.courseId,
                                @"version":VERSION,
                                @"uid":UID,
                                };
    __weak typeof(self) weakself = self;
    [CKHttpCommunicate createRequest:HTTP_IMANDARIN_NULL WithParam:parameter withMethod:GET success:^(id result) {
        if (result) {
            _jzCourseDM = [JZCourseDetailModel mj_objectWithKeyValues:result];
            //[chapterListArray removeAllObjects];
            for (int i = 0; i < _jzCourseDM.StepList.count; i++) {
                JZStepListModel *jzStepListM = [JZStepListModel mj_objectWithKeyValues:_jzCourseDM.StepList[i]];
                JrdChapterModel* chapterModel = [[JrdChapterModel alloc] init];
                chapterModel.ChapterIndex = jzStepListM.StepIndex;
                chapterModel.ChapterID = jzStepListM.StepID;
                chapterModel.ChapterName = jzStepListM.StepName;
                chapterModel.ChapterNodeNum = @"10";
                //chapterModel.NodeDuration = jzClassM.VideoTimeLength;
                [chapterListArray addObject:chapterModel];
            }
        }
        [weakself.tableView reloadData];
        [weakself.tableView.mj_header endRefreshing];
    } failure:^(NSError *erro) {
        [weakself.tableView.mj_header endRefreshing];
        
    } showHUD:nil];
    
}

- (void)setupTableview{
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //设置普通状态的动画图片
    NSMutableArray *idleImages = [NSMutableArray array];
    for (NSUInteger i = 1; i<=60; ++i) {
        UIImage *image = [UIImage imageNamed:@"icon_listheader_animation_1"];
        [idleImages addObject:image];
    }
    [header setImages:idleImages forState:MJRefreshStateIdle];
    
    //设置即将刷新状态的动画图片
    NSMutableArray *refreshingImages = [NSMutableArray array];
    UIImage *image1 = [UIImage imageNamed:@"icon_listheader_animation_1"];
    [refreshingImages addObject:image1];
    UIImage *image2 = [UIImage imageNamed:@"icon_listheader_animation_2"];
    [refreshingImages addObject:image2];
    [header setImages:refreshingImages forState:MJRefreshStatePulling];
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    //马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
}

#pragma mark - table View
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(0 == section){
        return 2;
    }else {
        return chapterListArray.count;
        /*if(0 == vHeadIndex){
         return chapterListArray.count;
         }else{
         return 1;
         }*/
    }
}


// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(0 == indexPath.section){
        static NSString *cellIndentifier = @"detailCell0";

        UITableViewCell* cell  =[tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        if(0 == indexPath.row){
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView];
            
            UIView *lineView_foot = [[UIView alloc] initWithFrame:CGRectMake(0, vCourseInfoCellHeight - 0.5, SCREEN_WIDTH, 0.5)];
            lineView_foot.tag = 10;
            lineView_foot.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView_foot];
        }else{
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 49.5, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView];
            
        }
        
        if(0 == indexPath.row){
            cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.text = _coursemodel.courseDes;//@"这是课程简介";
        }else{
            cell.textLabel.text =NSLocalizedString(@"jrd_learn_hours",nil);//@"这是课程学习时长";
            self.learn_time_label.text=@"00:12:00";
            cell.accessoryView= self.learn_time_label;
        }
        return cell;
    }else{
        static NSString *cellIndentifier = @"detailCell11";
        
        JrdCourseChpaterCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[JrdCourseChpaterCellTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
            //下划线
            UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(40, 63.5, SCREEN_WIDTH, 0.5)];
            lineView.tag = 10;
            lineView.backgroundColor = JrdSpeLineColor;
            [cell addSubview:lineView];
        }
        JrdChapterModel* chapterModel = chapterListArray[indexPath.row];
        [cell setJzClassMExt:chapterModel];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //UIView* view = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 40, 0, 40, 64)];
        /*UIButton* image= [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 36, 22, 20, 20)];
        [image setBackgroundImage:[UIImage imageNamed:@"ico_download"] forState:UIControlStateNormal];
        [image addTarget:self action:@selector(downloadClick) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = image;*/
        return cell;
    }
}

- (void)downloadClick{
    NSLog(@"zlwu download click");
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"下载错误" message:@"此课件暂不支持下载" delegate:self cancelButtonTitle:NSLocalizedString(@"jrd_OK", nil) otherButtonTitles:nil, nil];
    [alert show];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(0 == section){
        return NSLocalizedString(@"jrd_course_des", nil);//@"课程简介";
    }else{
        return NSLocalizedString(@"jrd_chapter", nil);//@"科目";
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        if(indexPath.row == 0){
            
            NSString *str = _coursemodel.courseDes;
            
            CGSize size = [str sizeWithFont:[UIFont systemFontOfSize:18.f] constrainedToSize:CGSizeMake((SCREEN_WIDTH - 16), MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
            
            vCourseInfoCellHeight = size.height+20;
            return vCourseInfoCellHeight;
        }else{
            return 45;
        }
    }else{
        //if(vHeadIndex == 0)
        //return 64;
        //else{
        return 64;//(SCREEN_HEIGHT - 110 - 55 - NAVIGATION_BAR_HEIGHT - STATUS_BAR_HEIGHT);
        //}
    }
}

- (void)OnTap1{
    vHeadIndex = 0;
    [self.tableView reloadData];
}

- (void)OnTap2{
    NSLog(@"onTap1");
    vHeadIndex = 1;
    [self.tableView reloadData];
    
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
    if (section == 0) {
        return nil;
    }
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 55)];
    headerView.backgroundColor = JrdNavigationBarColor;//JrdSelectColor;
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTap1)];
    //目录View
    UIView *view_1 = [[UIView alloc] initWithFrame:CGRectMake(2, 2, SCREEN_WIDTH/2 - 4, 55 - 4)];
    if(0 == vHeadIndex){ //view_1 highlight
        view_1.backgroundColor = JrdSelectColor;//JrdNavigationBarColor;
    }else{
        view_1.backgroundColor = [UIColor clearColor];
    }
    view_1.layer.cornerRadius = 1;
    // view_1.backgroundColor = JRD_RGB(100, 100, 100);
    
    //图
    UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH/2 - 4 - 25)/2, 5 - 2, 25, 25)];
    [imageView1 setImage:[UIImage imageNamed:@"course_catalog_icon"]];
    //[imageView1 addGestureRecognizer:tap1];
    [view_1 addSubview:imageView1];
    //文字
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView1.frame), SCREEN_WIDTH/2 -4, 20)];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.textColor = [UIColor whiteColor];
    label1.font = [UIFont systemFontOfSize:13];
    label1.text = @"目录";
    //[label1 addGestureRecognizer:tap1];
    [view_1 addSubview:label1];
    [view_1 addGestureRecognizer:tap1];
    
    [headerView addSubview:view_1];
    
    //图
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(OnTap2)];
    
    UIView *view_2 = [[UIView alloc] initWithFrame:CGRectMake(2 + (SCREEN_WIDTH/2), 2, SCREEN_WIDTH/2 - 4, 55 - 4)];
    if(1 == vHeadIndex){
        view_2.backgroundColor = JrdSelectColor;//JrdNavigationBarColor;
    }else{
        view_2.backgroundColor = [UIColor clearColor];//JRD_RGB(200, 200, 200);
        
    }
    view_2.layer.cornerRadius = 1;
    UIImageView *imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH/2 -4 - 25)/2, 5 - 2, 25, 25)];
    [imageView2 setImage:[UIImage imageNamed:@"course_info_icon"]];
    imageView2.userInteractionEnabled = YES;
    [view_2 addSubview:imageView2];
    
    //文字
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView1.frame), SCREEN_WIDTH/2 -4, 20)];
    
    label2.textAlignment = NSTextAlignmentCenter;
    label2.textColor = [UIColor whiteColor];
    label2.font = [UIFont systemFontOfSize:13];
    label2.text = @"详情";
    label2.userInteractionEnabled = YES;
    [view_2 addSubview:label2];
    [view_2 addGestureRecognizer:tap2];
    [headerView addSubview:view_2];
    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"zlwu add for select index");
    JrdChapterModel* chapterModel = chapterListArray[indexPath.row];

    JrdChapterNodeViewController* vc = [[JrdChapterNodeViewController alloc] init];
    vc.chaptermodel = chapterModel;
    vc.SID = self.coursemodel.SID;
    vc.courseId = self.coursemodel.courseId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)setFakeData
{
   // [self dataJson];
}


#pragma mark - Mark data
@end
